const path=require('path');
const {src,dest,series,parallel,watch}=require('gulp');
const sass=require('gulp-sass');
const connect=require('gulp-connect');
const webpack=require('webpack-stream');
const proxy=require('http-proxy-middleware');

function copyhtml(){
    return src('./src/*.html')
    .pipe(dest('./dev/'))
    .pipe(connect.reload())
    
}

function packScss(){
 return src('./src/styles/*.scss')
     .pipe(sass().on('error',sass.logError))
     .pipe(dest('./dev/styles/'))
    .pipe(connect.reload())

}

function copylibs(){
return src('./src/libs/**/*')
.pipe(dest('./dev/libs'))
}

function copyassets(){
    return src('./src/assets/**/*')
    .pipe(dest('./dev/assets'))
    }

 function packJs(){
return src('src/scripts/*.js')
.pipe(webpack({
    mode:'development',
    entry:{
     app:   './src/scripts/app.js',
    'app-first' : './src/scripts/app-first.js',
    'login' : './src/scripts/login.js',
    'register' : './src/scripts/register.js',
    'movie' : './src/scripts/movie.js',
    'search' : './src/scripts/search.js'
    },
    output:{
        path:path.resolve(__dirname,'./dev'),
        filename:'[name].js'
    },
    module:{
        rules:[
            {
                test:/\.art$/,
                loader:'art-template-loader'
            }
        ]
    }
    
}))
.pipe(dest('./dev/scripts/'))
.pipe(connect.reload())
} 

function startServer(){
  return  connect.server({
      name:'Dist App',
      root:'./dev',
      port:8000,
      host:'10.9.49.175',
      livereload:true,
      middleware:function(){
          return[
              proxy('/api',{
                  target:'https://m.lagou.com',
                  changeOrigin:true,
                  pathRewrite:{
                      '^/api': ''
                  }
              }),
              proxy('/apo',{
                target:'https://passport.lagou.com',
                changeOrigin:true,
                pathRewrite:{
                    '^/apo': ''
                }
            }),
            proxy('/apa',{
                target:'http://m.maoyan.com',
                changeOrigin:true,
                pathRewrite:{
                    '^/apa': ''
                }
            })          
          ]
      }
  })
}

function watchFiles(){
watch('./src/*.html',series(copyhtml))
watch('./src/libs/*',series(copylibs))
watch('./src/**/*',series(packJs))
watch('./src/**/*.scss',series(packScss))
watch('./src/assets/*',series(copyassets))
}

exports.default=series(parallel(copyhtml,copyassets,copylibs,packScss,packJs),parallel(startServer,watchFiles))

